﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;

namespace Asxsyd92Core.Utils.HttpUtility
{
    public class HttpHelper
    {
        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="accessToken">AccessToken</param>
        /// <param name="data">发送的模板数据</param>
        /// <returns></returns>
        public static string SendPost(string url, string data)
        {
            //  string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}", accessToken);
            HttpWebRequest hwr = WebRequest.Create(url) as HttpWebRequest;
            hwr.Method = "POST";
            hwr.ContentType = "application/x-www-form-urlencoded";
            byte[] payload;
            payload = System.Text.Encoding.UTF8.GetBytes(data); //通过UTF-8编码
            hwr.ContentLength = payload.Length;
            Stream writer = hwr.GetRequestStream();
            writer.Write(payload, 0, payload.Length);
            writer.Close();
            var result = hwr.GetResponse() as HttpWebResponse; //此句是获得上面URl返回的数据
            string strMsg = WebResponseGet(result);
            return strMsg;
        }
        public static string SendGet(string url)
        {
            try
            {
                HttpWebRequest hwr = WebRequest.Create(url) as HttpWebRequest;
                hwr.Method = "get";
                hwr.ContentType = "application/x-www-form-urlencoded";
                var result = hwr.GetResponse() as HttpWebResponse; //此句是获得上面URl返回的数据
                string strMsg = WebResponseGet(result);
                return strMsg;
            }
            catch (Exception ex)
            {
                Asxsyd92Core.Utils.Tools.createFile(ex.Message);
                return "";
            }
        }

        public static string WebResponseGet(HttpWebResponse webResponse)
        {
            StreamReader responseReader = null;
            string responseData = "";
            try
            {
                responseReader = new StreamReader(webResponse.GetResponseStream());
                responseData = responseReader.ReadToEnd();
            }
            catch
            {
                throw;
            }
            finally
            {
                webResponse.GetResponseStream().Close();
                responseReader.Close();
                responseReader = null;
            }
            return responseData;
        }

        /// <SUMMARY> 
        /// 上传多媒体文件,返回 MediaId 
        /// </SUMMARY> 
        /// <PARAM name="ACCESS_TOKEN"></PARAM> 
        /// <PARAM name="Type"></PARAM> 
        /// <PARAM name="filepath">本地服务器的地址</PARAM> 
        /// <RETURNS></RETURNS> 
        public string UploadwxMultimedia(string ACCESS_TOKEN, string Type, string filepath)
        {
            string result = "";
            string wxurl = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + ACCESS_TOKEN + "&type=" + Type;
            // string filepath = AppDomain.CurrentDomain.BaseDirectory + "WinXin/image" + "\\hemeng80.jpg"; //(本地服务器的地址)

            WebClient myWebClient = new WebClient();
            myWebClient.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                byte[] responseArray = myWebClient.UploadFile(wxurl, "POST", filepath);
                result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length);


            }
            catch (Exception ex)
            {
                result = "Error:" + ex.Message;
            }

            return result;
        }
        /// <SUMMARY> 
        /// 下载保存多媒体文件,返回多媒体保存路径 
        /// </SUMMARY> 
        /// <PARAM name="ACCESS_TOKEN"></PARAM> 
        /// <PARAM name="MEDIA_ID"></PARAM> 
        /// <RETURNS></RETURNS> 
        public string GetwxMultimedia(string ACCESS_TOKEN, string MEDIA_ID)
        {
            try
            {
                string file = string.Empty;
                string content = string.Empty;
                string strpath = string.Empty;
                string savepath = string.Empty;
                string stUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + ACCESS_TOKEN + "&media_id=" + MEDIA_ID;

                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(stUrl);

                req.Method = "GET";
                using (WebResponse wr = req.GetResponse())
                {
                    HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();
                    var fis = Guid.NewGuid().ToString();
                    fis = fis + DateTime.Now.ToString("yyyyMMddHHmmss");
                    strpath = myResponse.ResponseUri.ToString();

                    WebClient mywebclient = new WebClient();
                    savepath = AppDomain.CurrentDomain.BaseDirectory + "WinXin/Record" + "\\" + fis + ".amr";




                    string mp3SavePth = AppDomain.CurrentDomain.BaseDirectory + "WinXin/Record" + "\\" + fis + ".mp3";
                    try
                    {
                        mywebclient.DownloadFile(strpath, savepath);
                        file = savepath;
                    }
                    catch (Exception ex)
                    {
                        savepath = ex.ToString();
                    }
                    if (!string.IsNullOrEmpty(ConvertToMp3(savepath, mp3SavePth)))
                    {

                        //删除amr文件
                        if (File.Exists(savepath))
                        {
                            //参数1：要删除的文件路径
                            File.Delete(savepath);

                            return "WinXin/Record" + "\\" + fis + ".mp3";
                        }
                        else
                        {

                            return "";
                        }

                    }



                }

                return "";
            }
            catch (Exception ex)
            {

                return "";
            }
        }
        public string ConvertToMp3(string pathBefore, string pathLater)
        {
            string c = AppDomain.CurrentDomain.BaseDirectory + @"ffmpeg.exe -i " + pathBefore + " " + pathLater;
            string str = RunCmd(c);
            return str;
        }

        /// <summary>
        /// 执行Cmd命令
        /// </summary>
        private string RunCmd(string c)
        {
            try
            {
                ProcessStartInfo info = new ProcessStartInfo("cmd.exe");
                info.RedirectStandardOutput = false;
                info.UseShellExecute = false;
                Process p = Process.Start(info);
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.Start();
                p.StandardInput.WriteLine(c);
                p.StandardInput.AutoFlush = true;
                Thread.Sleep(1000);
                p.StandardInput.WriteLine("exit");
                p.WaitForExit();
                string outStr = p.StandardOutput.ReadToEnd();
                p.Close();

                return outStr;
            }
            catch (Exception ex)
            {
                return "error" + ex.Message;
            }
        }
    }
}
